package com.aisb.core.util.file;

import com.aisb.core.InitParam;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ExportExcelUtils {
    public static void exportExcel(HttpServletResponse response, String fileName) throws Exception {
        fileName = InitParam.FILE_PATH_DOWNLOAD + fileName;
        File file = new File(fileName);
        if (!file.exists()) {
            response.getWriter().print("文件下载失败，请重新下载");
            return;
        }

        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));


        OutputStream os = null;
        FileInputStream fis = null;
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            for (int read; (read = fis.read(buffer)) != -1; ) {
                os.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
